# encoding: utf-8

class PmsController < ApplicationController
  
  before_filter :require_login
  
  # Prikaz svih PM trenutnog korisnika
  def index
    @pms = Pm.order("created_at DESC").where(" `to` = ?", current_member.id )
  end

  # Prikaz pojedinog PMa
  def show
    @pm = Pm.find(params[:id])
    
    if @pm.to == current_member.id then
      @pm.read = true
      @pm.save
    end
  end

  # obrazac za slanje PMa
  def new
    @pm = Pm.new
    @members = Member.all
   
  end
  
  # metoda koja moze primiti primatelja iz URLa
  def sendto
    @pm = Pm.new
    @members = Member.all
    @pm.to = params[:to]
    
    unless params[:title].nil?
    	@pm.title = "RE: "+params[:title]
    end

    render :action => :new
  end

  # slanje tj. spremanje P<a
  def create
    @pm = Pm.new(params[:pm])
    @pm.read = false;
    @pm.from = current_member.id;

    if @pm.save
    	UserMailer.new_pm(@pm).deliver
      redirect_to(@pm, :notice => 'Privatna poruka je poslana.') 
    else
      render :action => "new" 
    end
  end

 	# brisanje PMa
  def destroy
    @pm = Pm.find(params[:id])
    @pm.destroy

    redirect_to(pms_url) 
  end
end
